# -*- coding=utf-8 -*-

"""
apply model
"""
from framework.redi import RedisModel
import re
import tornado.httpclient
import json

class ApplyModel(RedisModel):
    """apply user"""

    def __init__(self):
        """super init"""
        super(ApplyModel, self).__init__()

    def get_user_fuwa(self, start, size):
        """get user fuwa"""
        key = 'fuwa_apply'
        count = self.zcard(key)
        stop = start + size - 1
        datas = dict(recordsTotal=count, recordsFiltered=count)
        if start >= count:
            datas['data'] = list()
            return datas
        fuwas = self.zrange(key, start, stop)
        l = list()
        for fuwa_k in fuwas:
            fuwa = self.hgetall(fuwa_k)
            fuwa['key_id'] = fuwa_k.split('_')[2]
            fuwa['nature'] = 'i'
            if fuwa_k.find('fuwa_c_') == 0:
                fuwa['nature'] = 'c'
            l.append(fuwa)
        datas['data'] = l
        return datas

    def get_apply_user(self, start, size):
        """get user apply"""
        key = 'fuwa_apply_user'
        count = self.zcard(key)
        stop = start + size - 1
        datas = dict(recordsTotal=count, recordsFiltered=count)
        if start >= count:
            datas['data'] = list()
            return datas
        applys = self.zrange(key, start, stop, withscores=True)
        l = list()
        # https://api.66boss.com/ucenter/userinfo/nick?user_id=12222
        ids = list()
        for u in applys:
            user = dict()
            user['id'] = u[0]
            user['name'] = ''
            p = re.match(r'^([0-9]+)_apply$', u[0])
            if p:
                user['id'] = p.group(1)
                ids.append(user['id'])
            user['value'] = u[1]
            l.append(user)
        datas['data'] = l
        c = tornado.httpclient.HTTPClient()
        url = 'https://api.66boss.com/ucenter/userinfo/nick?user_id=%s' % ','.join(ids)
        try:
            res = c.fetch(url)
        except tornado.httpclient.HTTPError as e:
            print 'err: %s' % e
            return datas
        c.close()
        j = json.loads(res.body)
        if j['result']:
            for i in l:
                i['name'] = j['result'].get(i['id'])
        datas['data'] = l
        return datas
